'use strict';
const Service = require('egg').Service;
const fs = require('fs');
const path  =require('path');
const sendToWormhole= require('stream-wormhole');
//服务模板
//使用方法: 在控制器中 await ctx.service.serviceM.TEST(); //serviceM是本服务的文件名 ,TEST是方法
class UploadService extends Service {
  constructor(ctx) {
    // super(ctx);
    // this.root = 'https://localhost:7001';
  }


  async index (){
      const ctx = this.ctx;
      const stream = await ctx.getFileStream();
      const fileName=stream.filename;

      let target =  path.join('/',`app/public/${stream.filename}`);
      const result =await new Promise((resolve,reject)=>{
          const remoteFileStream=fs.createWriteStream(target);
          stream.pipe(remoteFileStream);
          let errFlag;

          remoteFileStream.on('error',err=>{
            errFlag = true;
            sendToWormhole(sream);
            remoteFileStream.destroy();
            reject(err);
          });
          remoteFileStream.on('finish',async()=>{
            if(errFlag) return;
            resolve({fileName,name:stream.fields.name});
          });
          
      });
      return result
  }
  // async create(params) {
  //   // console.log(999)
  //   return 'service 处理 ok';
  // }

  
 
}

module.exports = UploadService;


////////////////////////////////////////////////
// 'use strict';
// const fs = require('fs');
// const path = require('path');
// const Service = require('egg').Service;

// const awaitWriteStream = require('await-stream-ready').write;
// const sendToWormhole = require('stream-wormhole');
// const formidable = require("formidable");
// // const Controller = require('../../core/base_controller');
// class UploadService extends Service {
//  async parse(req) {
//   const form = new formidable.IncomingForm();
//   return new Promise((resolve, reject) => {
//    form.parse(req, (err, fields, files) => {
//     resolve({ fields, files })
//    })
//   });
//  }
//  /**
//  * 上传文件，兼容单文件和多文件
//  * @param customName 单文件自定义文件名
//  * @param isAjax 上传方式
//  */
//  async upload() {
//   const { ctx, logger } = this;
//   const extraParams = await this.parse(ctx.req);
//   let { multipleFile, customName, isAjax } = extraParams && extraParams['fields'];
//   logger.info(multipleFile, customName, isAjax);
//   if (isAjax === 'yes') {
//    const urls = [];
//    for (let key in extraParams.files) {
//     const file = extraParams.files[key];
//     logger.info('file.name', file.name);
//     logger.info('customName', customName);
//     const stream = fs.createReadStream(file.path);
//     const fileName = customName ? (customName + path.extname(file.name)) : file.name;
//     const target = path.join(this.config.baseDir, 'app/public/upload', fileName);
//     const writeStream = fs.createWriteStream(target);
//     try {
//      await awaitWriteStream(stream.pipe(writeStream));
//     } catch (err) {
//      await sendToWormhole(stream);
//      throw err;
//     }
//     urls.push(target);
//    }
//    this.success({ urls })
//   }
//  }
// }
// // module.exports = FileController;
// module.exports = UploadService;